import React, { Component } from 'react';
import { Table, Anchor, Collapse, Tree } from '@knownsec/react-component';
import s from './style.module.less';
import { timeColumns, riskColumns, webParams, securityParams, linkParams, scanTypeParams, scanProfileList,changeCheckParams} from "../columns"
import { getAppendix, getAppendixGroup } from '~/API';
import folderIcon from '@/assets/svg/folder.svg';
import netIcon from '@/assets/svg/net.svg';
import netgreyIcon from '@/assets/svg/netgrey.svg';
import regularIcon from '@/assets/svg/regular.svg';
import cn from 'classnames';
import { WARNING_SECURITYEVENT_MAP2, MONTOR_AVILIABLE_MAP } from '@/common/common.js';
const AVILIABLE_MAP={}
MONTOR_AVILIABLE_MAP.forEach(e=>{
    AVILIABLE_MAP[e.value]=e.label
})
const { Panel } = Collapse;
const { Link } = Anchor;
class Appendix extends Component {
  constructor(props) {
    super(props);
    this.caleData = [
      { grade: '严重', explain: '分置加权，加权后大于75分为：严重' },
      { grade: '高危', explain: '分置加权，大于50分且小于等于75分为：高危' },
      { grade: '中危', explain: '分置加权，大于25分且小于等于50分为：中危' },
      { grade: '低危', explain: '分置加权，大于0且小于等于25分为：低危' },
      { grade: '安全', explain: '分置加权，等于0分为：安全' },
    ];
    this.state = {
      alldata: {},
      timeData: [],
      treeData: [],
      loading: true
    }
  }
  componentDidUpdate(prevProps) {
    if(prevProps.sid && prevProps.sid != this.props.sid){
      this.getData();
    }
  }
  componentDidMount() {
    this.getData();
  }
  getData(){
    let Api = null
    if(this.props.sid){
      Api = getAppendixGroup(this.props.sid)
    }else{
      Api = getAppendix(this.props.targetId)
    }
    this.setState({ loading: true })
    Api.then(res => {
      if(res.status === 'success'){
        const detail = res.data?.detail
        let d = []
        Object.keys(detail).map(i=>d.push({item: scanTypeParams[i],started_at: detail[i].started_at,ended_at: detail[i].ended_at, task_id: detail[i].task_id}))
        this.setState({alldata: res.data, timeData: d, loading: false})
        if(res.data.structure && res.data.structure.length){
          const t = res.data.structure
          this.trunTree(t)
        }
      } else {
        this.setState({alldata: {}, timeData: [], loading: false})
      }
    }).catch(_ => {
        this.setState({alldata: {}, timeData: [], loading: false})
    })
  }
  trunTree(arr){
    var targetTree = []
    arr.forEach(item => {
      const node = item.path.split('/').filter(f => f)
      node.map((item,index) => {
        let key = '/'+item
        if(index>0){
          key = '/'+node.slice(0,index).join('/')+'/'+item
        }     
        const ntree = {
          title: item,
          key: key,
          icon: <img src={index==0?netIcon:((index==node.length-1)&&item.indexOf('.')>-1)?regularIcon:folderIcon} />,
          children: []
        }
        targetTree.push(ntree)
      })
    });
    // targetTree去重
    const hash = {};
    targetTree = targetTree.reduce((item, next)=>{
        hash[next.key] ? '' : hash[next.key] = true && item.push(next);
        return item;
    },[])
    this.deepAppendObj(targetTree)
    this.setState({treeData: targetTree})

  }
  // 递归插入节点
  deepAppendObj(arr){
    for (var i=0; i<arr.length;i++){
      const t=arr[i]
      const keyarr = t.key.split('/').filter(f => f);
      if(keyarr.length>1){
        const appdata = t
        function df(appdata2, arr2){
          arr2.forEach(a => {
            const akey = appdata2.key.split('/')
            // 父级key
            const pkey = akey.slice(0,akey.length-1).join('/')
            if(a.key === pkey){
              a.children.push(appdata2)
            }else{
              df(appdata2, a.children)
            }
          })
        }
        df(appdata,arr)
        const a = arr.splice(i--,1)
      }
    }
  }
  handleAnchorClick = (e) => {
    e.preventDefault();
  };
  //检测模块
  PanelMore=(item ,index)=>{
      const allData= this.state.alldata||{}
      let retDate=null
      if(item === 'vul' && allData?.vuln_name_list?.length){
        retDate= allData.vuln_name_list.map((v) => <p>|--{v}</p>)
      }else if(item === 'availability' && allData?.job_config_map?.availability?.include_plugins.length){
        retDate=  allData?.job_config_map?.availability.include_plugins.map((v) =>{ 
          
            return <p>|--{AVILIABLE_MAP[v]}</p>
        })
      }else if(item === 'securityEvent' && allData?.job_config_map?.securityEvent?.include_plugins.length){
        retDate=  allData?.job_config_map?.securityEvent.include_plugins.map((v) => <p>|--{WARNING_SECURITYEVENT_MAP2[v]}</p>)
      }
      return  (<Panel showArrow={false} header={scanTypeParams[item]} key={index}>
                      {retDate}
                    </Panel>)
      
  }
  render() {
    let type=null;
    if(this.state.alldata?.detail){
        type= Object.keys(this.state.alldata?.detail)[0]
    }
    const tSystem_version=type?this.state.alldata?.detail[type]?.extra?.system_version:'--'
    const tData_version=type?this.state.alldata?.detail[type]?.extra?.data_version:'--'
    return (
      <div className={s.wangappendix}>
        <Anchor
          className={s.anchoritem}
          onClick={this.handleAnchorClick}
          getContainer={() => document.getElementById('wo')}
        >
          <Link href="#basic-tree" title="业务系统结构目录树" />
          <Link href="#security-calc" title="安全指数计算" />
          <Link href="#param-detail" title="检测参数详情" />
          <Link href="#time-detail" title="检测时间详情" />
          <Link href="#version" title="检测版本" />
        </Anchor>
        <div id="wo" className={s.wo}>
          <div id="basic-tree" className={s.title}>
            业务系统结构目录树
          </div>
          <Collapse defaultActiveKey={['1']} expandIconPosition="right">
            <Panel
              className={s.mytree}
              header={
                <span>
                  <img src={netgreyIcon} />
                  &ensp;{this.state.alldata.target_url}
                </span>
              }
              key="1"
            >
              <div className={s.dangerous}>
                <Tree showIcon defaultExpandAll treeData={this.state.treeData} />
              </div>
            </Panel>
          </Collapse>
          <div id="security-calc" className={s.title}>
            安全指数计算
          </div>
          <Table 
            columns={riskColumns} 
            data={this.caleData}></Table>
          <div id="param-detail" className={s.title}>
            检测参数详情
          </div>
          <div className={s.paramitem}>
            <div className={s.subtitle}>检测业务系统</div>
            <div className={cn(s.itemwrap, s.greystyle)}>
              <p>{this.state.alldata.target_url || '-'}</p>
            </div>
            <div className={s.subtitle}>检测模块</div>
            <div className={s.itemwrap}>
              <Collapse defaultActiveKey={[1,2,4]} ghost>
                {this.state.alldata?.modules?.map((item, index) => {
                  return (this.PanelMore(item,index))
                })}
              </Collapse>
            </div>
            {(!this.props.type || this.props.type === 'securityEvent') && (
              <>
                <div className={s.subtitle}>安全事件监测参数</div>
                <div className={s.itemflex}>
                  {securityParams.map((item) => {
                    return (
                      <div className={s.wrapflex}>
                        {item.name}：
                        {item.key === 'crawler_scope'
                          ? this.state.alldata?.job_config_map?.securityEvent[item.key] == 2
                            ? '全量爬取'
                            : '指定页面'
                          : item.key === 'evidence'
                          ? this.state.alldata?.job_config_map?.securityEvent[item.key]
                            ? '是'
                            : '否'
                          : this.state.alldata?.job_config_map?.securityEvent[item.key] || '暂无'}
                      </div>
                    );
                  })}
                </div>
              </>
            )}
            {(!this.props.type || this.props.type === 'vul') && (
              <>
                <div className={s.subtitle}>漏洞检测参数</div>
                <div className={s.itemflex}>
                  {webParams.map((item) => {
                    return (
                      <div className={s.wrapflex}>
                        {item.name}：
                        {item.key === 'scan_profile'
                          ? scanProfileList[this.state.alldata?.job_config_map?.vul[item.key] + 1]
                          : this.state.alldata?.job_config_map?.vul[item.key] || '暂无'}
                      </div>
                    );
                  })}
                </div>
              </>
            )}
            {(!this.props.type || this.props.type === 'risk_link') && (
              <>
                <div className={s.subtitle}>外链检测参数</div>
                <div className={s.itemflex}>
                  {linkParams.map((item) => {
                    return (
                      <div className={s.wrapflex}>
                        {item.name}：
                        {this.state.alldata?.job_config_map?.risk_link[item.key] || '自动'}
                      </div>
                    );
                  })}
                </div>
              </>
            )}
            {(!this.props.type || this.props.type === 'change_check') && (
              <>
                <div className={s.subtitle}>篡改事件监测参数</div>
                <div className={s.itemflex}>
                  {changeCheckParams.map((item) => {
                    let text=this.state.alldata?.job_config_map?.change_check[item.key]
                    if(item.key === 'crawler_scope'){
                      text=this.state.alldata?.job_config_map?.change_check[item.key] == 2
                      ? '全量爬取'
                      : '指定页面'
                    }
                    const arr={is_check_text:'text_change_ratio',is_check_structure:'structure_change_ratio',is_check_resource:'resource_change_ratio'}
                    if(arr[item.key]){
                      text= this.state.alldata?.job_config_map?.change_check[item.key]
                      ? '启用': '禁用'
                      text+=`(${(this.state.alldata?.job_config_map?.change_check[arr[item.key]]*100).toFixed(2)}%)`
                    }
                    return (
                      <div className={s.wrapflex}>
                        {item.name}：{text}
                      </div>
                    );
                  })}
                </div>
              </>
            )}
          </div>
          <div id="time-detail" className={s.title}>
            检测时间详情
          </div>
          <Table 
            columns={timeColumns} 
            data={this.state.timeData}
            tableLoading={this.state.loading}
            loadingLabel=""
            ></Table>
          <div id="version" className={s.title}>
            检测版本
          </div>
          <div className={cn(s.itemwrap, s.greystyle)}>
            <p>系统版本：{tSystem_version||'--'}</p>
            <p>插件版本：{tData_version||'--'}</p>
          </div>
        </div>
      </div>
    );
  }
}

export default Appendix;
